const socketClientManager = require("../modules/socketClient");

async function socketClientRoutes(fastify, options) {
  // 注册WebSocket路由
  fastify.get("/ws", { websocket: true }, (connection, req) => {
    const moduleType = req.query.module;

    // 基本参数验证
    if (!moduleType) {
      connection.socket.send(
        JSON.stringify({
          type: "error",
          code: 4000,
          reason: "缺少必要参数",
        })
      );
      connection.socket.close();
      return;
    }

    // 处理WebSocket连接
    socketClientManager.handleConnection(connection, moduleType);
  });

  // 注册示例模块处理器
  socketClientManager.registerHandler("chat", async (data) => {
    // 这里处理聊天模块的消息
    if (data.type === "data") {
      // TODO: 处理聊天消息，例如保存到MongoDB
      return {
        type: "data",
        module: "chat",
        payload: {
          status: "received",
        },
        timestamp: Date.now(),
      };
    }
  });

  socketClientManager.registerHandler("notify", async (data) => {
    // 这里处理通知模块的消息
    if (data.type === "data") {
      // TODO: 处理通知消息
      return {
        type: "data",
        module: "notify",
        payload: {
          status: "processed",
        },
        timestamp: Date.now(),
      };
    }
  });
  // 注册上传模块处理器
  socketClientManager.registerHandler("upload", async (data) => {
    // 处理上传模块的消息
    if (data.type === "progress") {
      // 处理上传进度消息
      return {
        type: "progress",
        module: "upload",
        payload: {
          status: "received",
          progress: data.progress,
          identifier: data.identifier,
          chunkIndex: data.chunkIndex,
        },
        timestamp: Date.now(),
      };
    } else if (data.type === "complete") {
      // 处理上传完成消息
      return {
        type: "complete",
        module: "upload",
        payload: {
          status: "success",
          url: data.url,
          identifier: data.identifier,
        },
        timestamp: Date.now(),
      };
    }
  });
  socketClientManager.registerHandler("ueProject", async (data) => {
    // 处理上传模块的消息
    console.log(data);
  });

  socketClientManager.registerHandler("ueInstance", async (data) => {
    // 处理上传模块的消息
    console.log(data);
  });
}

module.exports = socketClientRoutes;
